package com.example.rocketmq.consumer.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert;

import java.util.function.Consumer;
import java.util.function.Function;

@Configuration
public class FunctionConfig {

    // 定义了一个java.util.function.Consumer类型的consumer函数，它负责处理接收到的消息
    // 消费者函数consumer标记为@Bean，这样它会被Spring识别为一个消息监听器，并将其绑定到输入通道
    @Bean
    public Consumer<String> consumer() {
        return message -> {
            System.out.println("Received message 1: " + message);
            // 在这里添加处理接收到的消息的业务逻辑
        };
    }


    @Bean
    public Consumer<String> consumerUser() {
        return message -> {
            System.out.println("Received message 2: " + message);
            // 在这里添加处理接收到的消息的业务逻辑
        };
    }

    // 函数式组合，参考 https://docs.springjava.cn/spring-cloud-stream/reference/spring-cloud-stream/producing-and-consuming-messages.html#polling-configuration-properties
    @Bean
    public Function<Message<String>, Message<String>> enrich() {
        return message -> {
            Assert.isTrue(!message.getHeaders().containsKey("foo"), "Should NOT contain 'foo' header");
            return MessageBuilder.fromMessage(message).setHeader("foo", "bar").build();
        };
    }

    @Bean
    public Function<Message<String>, Message<String>> echo() {
        return message -> {
            Assert.isTrue(message.getHeaders().containsKey("foo"), "Should contain 'foo' header");
            System.out.println("Incoming message " + message);
            return message;
        };
    }

}
